package com.rihel.dao;

import com.rihel.model.User;
import com.rihel.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {



    public User getUserByUname(String uname) {
        try {
            return getUser("uname",uname);
        } catch (SQLException e) {
            return null;
        }
    }
    public User getUserById(Integer id) throws SQLException{
        try {
            return getUser("id",id);
        } catch (SQLException e) {
            return null;
        }

    }

    public boolean isRegister(String uname){
        User user = getUserByUname(uname);
        if(user==null){
            return false;
        }else{
            return true;
        }
    }




    private static User getUser(String str,Object value) throws SQLException {
        Connection conn = DBUtil.getconn();
        User user = null;

        PreparedStatement psm = conn.prepareStatement("SELECT * FROM user WHERE "+str+"=?");

        if(value instanceof Integer){
            psm.setInt(1, (Integer) value);
        }else if(value instanceof String){
            psm.setString(1, (String) value);
        }

        ResultSet rs = psm.executeQuery();
        if(rs.next()){
            user=generatorUserForResultSet(rs);
        }
        return user;
    }



    private static User generatorUserForResultSet(ResultSet resultSet) throws SQLException {
        User user =new User();
        user.setId(resultSet.getInt("id"));
        user.setUname(resultSet.getString("uname"));
        user.setPwd(resultSet.getString("pwd"));
        user.setAge(resultSet.getInt("age"));
        user.setGender(resultSet.getString("gender"));
        user.setMobile(resultSet.getString("mobile"));
        resultSet.close();
        return user;
    }

    public void addUser(User user) throws SQLException {
        Connection connection = DBUtil.getconn();
        PreparedStatement prss = connection.prepareStatement("INSERT INTO user (uname, pwd, mobile) VALUES (?,?,?)");
        prss.setString(1,user.getUname());
        prss.setString(2,user.getPwd());
        prss.setString(3,user.getMobile());
     prss.execute();

    }

}
